package com.elecbook.base.util;




import com.elecbook.base.constant.TextAutoFillConstant;
import com.elecbook.base.enums.OperationType;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @description 自动填充时间的工具类，除去时间还可以自动填充操作人
 * @author zken
 * @CreateDate 2024/10/19 19:50:06
 */
public class TimeFillUtil {
    /**
     * @description 泛型工具类，
     * 反射填充部分字段
     * @author zken
     * @CreateDate 2024/10/19 19:47:59
     */
    public static <T> T fillTimeAndCreateUser(T obj, OperationType operationType) {
        LocalDateTime now = LocalDateTime.now();
        Integer currentId = SecurityUtil.getCurrentId();
        //根据不同操作类型，为对应的属性通过反射赋值
        if (operationType == OperationType.INSERT) {
            try {
                Method setCreateTime = obj.getClass().getDeclaredMethod(TextAutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = obj.getClass().getDeclaredMethod(TextAutoFillConstant.SET_CREATE_USER, Integer.class);
                Method setUpdateTime = obj.getClass().getDeclaredMethod(TextAutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = obj.getClass().getDeclaredMethod(TextAutoFillConstant.SET_UPDATE_USER, Integer.class);

                //通过反射赋值
                setCreateTime.invoke(obj, now);
                setCreateUser.invoke(obj, currentId);
                setUpdateTime.invoke(obj, now);
                setUpdateUser.invoke(obj, currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (operationType == OperationType.UPDATE) {
            try {
                Method setUpdateTime = obj.getClass().getDeclaredMethod(TextAutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = obj.getClass().getDeclaredMethod(TextAutoFillConstant.SET_UPDATE_USER, Long.class);

                //通过反射赋值
                setUpdateTime.invoke(obj, now);
                setUpdateUser.invoke(obj, currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }


        return obj;
    }
}
